package com.xframe.domain.views.builder;

import com.xframe.domain.BaseModel;
import com.xframe.domain.emnus.Constant;
import com.xframe.domain.emnus.XDelFlag;
import com.xframe.domain.role.IUserCredentials;
import com.xframe.domain.sys.SysModel;
import com.xframe.domain.sys.SysModelAttr;
import com.xframe.domain.sys.SysModelConfig;
import com.xframe.domain.sys.SysModelViewConfig;
import com.xframe.domain.views.IModelConfigBuilder;
import com.xframe.xdal.core.model.mapping.IRelation;
import lombok.extern.log4j.Log4j2;

import java.util.ArrayList;
import java.util.List;

@Log4j2
public abstract class UIModelBuilder implements IModelConfigBuilder {

    @Override
    public List<SysModelConfig> builder(SysModel sysModel, IUserCredentials userCredentials) {
        SysModelViewConfig sysModelViewConfig = SysModelViewConfigCreate(sysModel,userCredentials);
        String json = setSysModelViewConfigContent(sysModel,userCredentials);
        log.info(json);
        sysModelViewConfig.setContent(json);
        List<SysModelConfig> sysModelConfigs = new ArrayList<>();
        sysModelConfigs.add(sysModelViewConfig);
        return sysModelConfigs;
    }

    public abstract String getViewName();
    public abstract String getConfigType();
    public abstract String getRenderClass();

    public String getParameter(){
        return "";
    }

    public abstract String setSysModelViewConfigContent(SysModel sysModel, IUserCredentials userCredentials);


    protected IRelation findRefAttr(SysModelAttr modelAttr, SysModel sysModel){
        List<IRelation> relationList = sysModel.getBelongsToMappingList();
        if(relationList == null || relationList.size() == 0){
            return null;
        }
        for(IRelation relation : relationList){
            if(relation.getForeignKey().equals(modelAttr.getAttrName())){
                return relation;
            }
        }
        return null;
    }



    protected SysModelViewConfig SysModelViewConfigCreate(SysModel sysModel,IUserCredentials userCredentials){
        SysModelViewConfig sysModelViewConfig = new SysModelViewConfig();
        sysModelViewConfig.setViewName(this.getViewName());
        sysModelViewConfig.setConfigType(this.getConfigType());
        sysModelViewConfig.setModelCode(sysModel.getModelCode());
        sysModelViewConfig.setRenderClass(this.getRenderClass());
        sysModelViewConfig.setSystemFlag(Constant.DEF_SYSTEMFLAG);
        sysModelViewConfig.setParameter(this.getParameter());
        sysModelViewConfig.setLanguage(Constant.DEF_LANGUAGE);
        sysModelViewConfig.setQueryKey(Constant.DEF_QUERY_KEY);
        sysModelViewConfig.setVer(Constant.DEF_VER);
        sysModelViewConfig.setBaseAttrVal(userCredentials);
        sysModelViewConfig.setDelFlag(XDelFlag.getDefFlag());

        return sysModelViewConfig;
    }
}
